import {
	createRouter
} from '@gowiny/uni-router';
import PAGE_DATA from '@/pages.json';

import {
	getAuthorization
} from './auth.js';

const reLaunchLogin = ref(false)

// app初次启动页面拦截的问题
export function launchFn() {
	// 没有token调整登录页面
	if (!getAuthorization()) {
		reLaunchLogin.value = true;
		uni.reLaunch({
			url: '/pages/login/login',
			success: () => {
				// #ifdef APP-PLUS
				plus.navigator.closeSplashscreen();
				// #endif
			}
		});
	} else {
		//存在则关闭启动页进入首页
		// #ifdef APP-PLUS
		plus.navigator.closeSplashscreen();
		// #endif
	}
}

// 白名单，支持正则表达式
const whiteList = [{
		pattern: /^\/pages\/login\/*/
	}, ],
	router = createRouter({
		pageData: PAGE_DATA
	});

function whiteFn(url) {
	return whiteList.some((item) => {
		if (typeof item === 'object' && item.pattern) return item.pattern.test(url);
		return url === item;
	});
}
/**
 * 路由守卫
 */
router.beforeEach((to, from) => {
	// 不是白名单并且没有token
	if (!whiteFn(to.path) && !getAuthorization() && !reLaunchLogin.value) {
		uni.reLaunch({
			url: '/pages/login/login',
		});
	}
});

export default router;